from django.shortcuts import render, redirect
from django.views import View
from student.models import Student

# Create your views here.
class FormView(View):

    def get(self, request):
        name = request.session.get("student_name", False)
        if name:
            del(request.session["student_name"])
            students = Student.objects.filter(name=name)
            print(students)
        else:
            students = Student.objects.all()

        return render(request, "form.html", {
            "name": name,
            "students": students
        })

    def post(self, request):
        name = request.POST.get("student_name")
        print(name)
        request.session["student_name"] = name
        return redirect(request.path)
# 增加一个学生
class AddStudent(View):
    def get(self, request):
        return render(request, "add.html")

    def post(self, request):
        name = request.POST.get("name")
        age = request.POST.get("age")
        email = request.POST.get("email")
        address = request.POST.get("address")
        phone = request.POST.get("phone")
        student = Student(name=name, age=age, email=email, address=address, phone=phone)
        student.save()
        return redirect("search")
    

# 删除一个学生
class DeleteStudent(View):
    def post(self, request):
        selected_ids = request.POST.getlist("selected_students")
        if selected_ids:
            students_to_delete = [Student.objects.get(id=student_id) for student_id in selected_ids]
            for student in students_to_delete:
                student.delete()
        return redirect("search")
# 修改一个学生
class UpdateStudent(View):

    def get(self, request):
        student_id = request.GET.get('id')
        student = Student.objects.get(id=student_id)
        return render(request, 'update_student.html', {'student': student})

    def post(self, request):
        student_id = request.POST.get('id')
        student = Student.objects.get(id=student_id)
        student.name = request.POST.get('name')
        student.age = request.POST.get('age')
        student.email = request.POST.get('email')
        student.address = request.POST.get('address')
        student.phone = request.POST.get('phone')
        student.save()
        return redirect('search')